package com.mingtu.jgspatrol.fragment;

import android.graphics.Color;
import android.os.Build;
import android.view.View;
import android.widget.RadioGroup;

import androidx.annotation.RequiresApi;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.listener.OnOptionsSelectChangeListener;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.formatter.ValueFormatter;
import com.github.mikephil.charting.interfaces.datasets.ILineDataSet;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.hjq.gson.factory.GsonFactory;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;
import com.mingtu.common.base.BaseBindingFragment;
import com.mingtu.common.callback.StringDialogCallback;
import com.mingtu.common.utils.Constant;
import com.mingtu.common.utils.MyLogUtil;
import com.mingtu.common.utils.MyUtills;
import com.mingtu.common.viewpager.LazyViewPager.LazyFragmentPagerAdapter;
import com.mingtu.contacts.bean.ContactsDeptBean;
import com.mingtu.jgspatrol.R;
import com.mingtu.jgspatrol.adapter.ResultRankingAdapter;
import com.mingtu.jgspatrol.bean.GradeBean;
import com.mingtu.jgspatrol.bean.TrackTrendBean;
import com.mingtu.jgspatrol.databinding.FragmentTrackDataBinding;
import com.mingtu.jgspatrol.utils.MyConstant;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;


public class TrackDataFragment extends BaseBindingFragment<FragmentTrackDataBinding> implements LazyFragmentPagerAdapter.Laziable {
    public static final int[] COLORS = {
            Color.rgb(153, 211, 163), Color.rgb(244, 183, 122)};
    private List<GradeBean.PageBean.ListBean> Databean = new ArrayList<>();
    private ResultRankingAdapter resultRankingAdapter;
    private OptionsPickerView pvOptions;
    private List<ContactsDeptBean.ListBean> dataBeans;
    private List<String> deptList = new ArrayList<>();
    private int[] positionArray = {0};
    private String[] dateArray = {"year", "month", "week"};
    private String dataStr1 = dateArray[0];
    private String dataStr2 = dateArray[1];
    private String deptId = "";

    public static TrackDataFragment getInstance() {
        TrackDataFragment ef = new TrackDataFragment();
        return ef;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_track_data;
    }

    @Override
    protected void initData() {
        binding.radioGroup1.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                //本年  本月 本周
                switch (checkedId) {
                    case R.id.rb_but11:
                        dataStr1 = dateArray[0];
                        break;
                    case R.id.rb_but12:
                        dataStr1 = dateArray[1];
                        break;
                }
                getTrackTotal();
            }
        });

        binding.radioGroup2.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                //月榜  周榜
                switch (checkedId) {
                    case R.id.rb_but21:
                        dataStr2 = dateArray[0];
                        break;
                    case R.id.rb_but22:
                        dataStr2 = dateArray[1];
                        break;
                }
                getTrackTop();
            }
        });
        addClickListener(this, binding.tvDept);
    }

    @Override
    protected void initView() {
    }

    @Override
    protected void getData() {
        getTrackTotal();
        getTrackTop();
        getTrackTrend();
        getDeptData();

        LinearLayoutManager manager1 = new LinearLayoutManager(context);
        binding.recyclerRank.setLayoutManager(manager1);

        resultRankingAdapter = new ResultRankingAdapter(context, Databean);
        binding.recyclerRank.setAdapter(resultRankingAdapter);
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.tv_dept:
                initOptionPicker();
                break;
        }
    }

    public void initLineChartData(List<TrackTrendBean.TaskNumBean> taskNumBeans) {
        int xLableCount = taskNumBeans.size();
        binding.lineChart.getDescription().setEnabled(false);
        binding.lineChart.setDrawGridBackground(false);
        binding.lineChart.setScaleEnabled(false);//不缩放
        binding.lineChart.getAxisRight().setEnabled(false);
        binding.lineChart.setExtraOffsets(0, 00, 0, 0);
//        MyMarkerView myMarkerView = new MyMarkerView(getActivity(), R.layout.layout_chart_marker_view);
//        myMarkerView.setChartView(binding.lineChart);
//        binding.lineChart.setMarker(myMarkerView);

        Legend l = binding.lineChart.getLegend();
        l.setVerticalAlignment(Legend.LegendVerticalAlignment.BOTTOM);
        l.setHorizontalAlignment(Legend.LegendHorizontalAlignment.LEFT);
        l.setOrientation(Legend.LegendOrientation.HORIZONTAL);
        l.setDrawInside(false);
        l.setEnabled(false);


        int XLabelCount = 5;
        if (taskNumBeans.size() % 2 == 0) {
            XLabelCount = 6;
        }

        XAxis xAxis = binding.lineChart.getXAxis();
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
        xAxis.setLabelCount(XLabelCount);
        xAxis.setDrawGridLines(true);
        xAxis.setDrawAxisLine(false);
        xAxis.setAxisMinimum(0);
        xAxis.setGranularity(1f);
        xAxis.setGridColor(getResources().getColor(R.color.bg_color_c1c));
        xAxis.setTextColor(getResources().getColor(R.color.text_color999));

        xAxis.setValueFormatter(new ValueFormatter() {
            @Override
            public String getFormattedValue(float value) {
                MyLogUtil.e("xxxLine", "value=" + value);
                int MyValue = (int) value;
                if (value < 0 || MyValue > taskNumBeans.size() - 1) {
                    return "";
                }
                String[] data = taskNumBeans.get(MyValue).getRq().split("-");
                return data[1];
            }
        });

        List<Integer> numList = new ArrayList<>();

        for (int i = 0; i < taskNumBeans.size(); i++) {
            int num = taskNumBeans.get(i).getNum();
            numList.add(num);
        }

        int YLabelCount = 5;
        if (Collections.max(numList) % 2 == 0) {
            //偶数的时候 设置为6  奇数的时候设置为5
            YLabelCount = 6;
        }

        YAxis leftAxis = binding.lineChart.getAxisLeft();
        leftAxis.setLabelCount(YLabelCount, false);
        leftAxis.setAxisMinimum(0); // this replaces setStartAtZero(true)
        leftAxis.setGranularity(1f);
        leftAxis.setGridColor(getResources().getColor(R.color.text_color333));
        leftAxis.setTextColor(getResources().getColor(R.color.text_color333));


        YAxis rightAxis = binding.lineChart.getAxisRight();
//        rightAxis.setTypeface(mTf);
        rightAxis.setLabelCount(YLabelCount, false);
        rightAxis.setDrawGridLines(false);
        rightAxis.setAxisMinimum(0); // this replaces setStartAtZero(true)
        rightAxis.setGranularity(1f);
        rightAxis.setGridColor(getResources().getColor(R.color.text_color333));
        rightAxis.setTextColor(getResources().getColor(R.color.text_color333));


        // set data
        binding.lineChart.setData((LineData) generateDataLine(taskNumBeans));

        // do not forget to refresh the chart
        binding.lineChart.invalidate();
        binding.lineChart.animateX(750);

    }

    private LineData generateDataLine(List<TrackTrendBean.TaskNumBean> taskNumBeans) {


        ArrayList<Entry> e1 = new ArrayList<Entry>();

        for (int i = 0; i < taskNumBeans.size(); i++) {
            int num = taskNumBeans.get(i).getNum(); //顾客数

            e1.add(new Entry(i, num));

        }

        LineDataSet d1 = new LineDataSet(e1, "New DataSet " + ", (1)");

        d1.setLineWidth(2f);
        d1.setCircleRadius(6f);
        d1.setCircleHoleRadius(3f);
        d1.setDrawCircleHole(true);
        d1.setCircleColor(Color.argb(76, 153, 211, 163));
        d1.setCircleHoleColor(Color.rgb(78, 171, 94));
        d1.setHighLightColor(Color.rgb(153, 211, 163));
        d1.setColor(Color.rgb(153, 211, 163));
        d1.setDrawValues(false);
        d1.setMode(LineDataSet.Mode.CUBIC_BEZIER);


        ArrayList<ILineDataSet> sets = new ArrayList<ILineDataSet>();
        sets.add(d1);
        LineData cd = new LineData(sets);
        return cd;
    }

    /**
     * 巡护总数据
     */
    private void getTrackTotal() {
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("type", dataStr1);
        String str = GsonUtils.toJson(hashMap);
        OkGo.<String>post(MyConstant.POST_TASK_STA_TOTAL3)
                .tag(this)
                .upJson(str)
                .execute(new StringDialogCallback(getActivity()) {
                    @Override
                    public void onSuccess(Response<String> response) {
                        String result = response.body();
                        if (!StringUtils.isEmpty(result)) {
                            JSONObject jsonObject = JSON.parseObject(result);
                            JSONObject dataObject = jsonObject.getJSONObject("data");
                            String duration = dataObject.getString("totalDuration");
                            String taskNum = dataObject.getString("taskNum");
                            String totalMileage = dataObject.getString("totalMileage");
                            String clockNum = dataObject.getString("clockNum");


                            if (!StringUtils.isEmpty(totalMileage)) {
                                binding.tvTotalMileage.setText(totalMileage + "");
                            } else {
                                binding.tvTotalMileage.setText("0");
                            }

                            if (!StringUtils.isEmpty(taskNum)) {
                                binding.tvTotalDayNum.setText(taskNum + "");
                            } else {
                                binding.tvTotalDayNum.setText("0");
                            }

                            if (!StringUtils.isEmpty(duration)) {
                                long d = 0;
                                if (duration.indexOf(".") != -1) {
                                    String array[] = duration.split("\\.");
                                    d = Long.parseLong(array[0]);
                                } else {
                                    d = Long.parseLong(duration);
                                }
                                binding.tvTotalTime.setText(MyUtills.formatSeconds2(d));
                            } else {
                                binding.tvTotalTime.setText("0");
                            }


                        }
                    }
                });
    }

    /**
     * 巡护排行榜
     */
    private void getTrackTop() {
        List<String> deptIdList = new ArrayList<>();
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("curPage", 1);
        hashMap.put("pageSize", Constant.PAGE_SIZE);
        hashMap.put("type", dataStr2);
        if (!deptId.equals("00") && !StringUtils.isEmpty(deptId)) {
            deptIdList.add(deptId);
        }
        hashMap.put("deptIdList", deptIdList);
        String str = GsonUtils.toJson(hashMap);
        OkGo.<String>post(MyConstant.POST_TASK_STA_TOP2)
                .tag(this)
                .upJson(str)
                .execute(new StringDialogCallback(getActivity()) {
                    @Override
                    public void onSuccess(Response<String> response) {
                        String result = response.body();
                        if (!StringUtils.isEmpty(result)) {
                            try {
                                Gson gson = GsonFactory.getSingletonGson();
                                GradeBean gradeBean = new GradeBean();
                                gradeBean = gson.fromJson(result, GradeBean.class);

                                List<GradeBean.PageBean.ListBean> listBeans = gradeBean.getPage().getList();

                                try {
                                    binding.recyclerRank.setVisibility(View.VISIBLE);
                                    binding.emptyLayout.setIsShowView(false);


                                    if (listBeans != null) {
                                        if (listBeans.size() > 0) {
                                            if (listBeans.size() > 10) {
                                                List<GradeBean.PageBean.ListBean> myListBeans = listBeans.subList(0, 10);
                                                resultRankingAdapter.upData(myListBeans);
                                            } else {
                                                resultRankingAdapter.upData(listBeans);
                                            }
                                        } else {
                                            binding.recyclerRank.setVisibility(View.GONE);
                                            binding.emptyLayout.setIsShowView(true);
                                        }
                                    } else {
                                        binding.recyclerRank.setVisibility(View.GONE);
                                        binding.emptyLayout.setIsShowView(true);
                                    }

                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            } catch (JsonSyntaxException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                });
    }


    /**
     * 巡护趋势
     */
    private void getTrackTrend() {
        OkGo.<String>post(MyConstant.POST_TASK_STA_TREND)
                .tag(this)
                .upJson("")
                .execute(new StringDialogCallback(getActivity()) {
                    @RequiresApi(api = Build.VERSION_CODES.O)
                    @Override
                    public void onSuccess(Response<String> response) {
                        String result = response.body();
                        if (!StringUtils.isEmpty(result)) {
                            Gson gson = GsonFactory.getSingletonGson();
                            TrackTrendBean trackTrendBean = new TrackTrendBean();
                            trackTrendBean = gson.fromJson(result, TrackTrendBean.class);
                            List<TrackTrendBean.TaskNumBean> taskNumBeans = trackTrendBean.getTaskNum();
                            binding.layoutLineChart.setVisibility(View.GONE);
                            binding.emptyLayout.setIsShowView(true);
                            if (taskNumBeans != null) {
                                if (taskNumBeans.size() > 0) {
                                    binding.layoutLineChart.setVisibility(View.VISIBLE);
                                    binding.emptyLayout.setIsShowView(false);
                                    initLineChartData(taskNumBeans);
                                }
                            }
                        }
                    }
                });
    }

    /**
     * 刷新数据
     */
    public void refresh() {
        getTrackTotal();
        getTrackTop();
        getTrackTrend();
        getDeptData();
    }

    /**
     * 条件选择器
     */

    private void initOptionPicker() {//条件选择器初始化

        pvOptions = new OptionsPickerBuilder(context, new OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {

                String deptName = deptList.get(options1);
                deptId = dataBeans.get(options1).getDeptId();
                binding.tvDept.setText(deptName);
                positionArray[0] = options1;
                getTrackTop();
            }
        })

                .setContentTextSize(20)//设置滚轮文字大小
                .setDividerColor(Color.LTGRAY)//设置分割线的颜色
                .setSelectOptions(0)//默认选中项
                .setBgColor(Color.WHITE)
                .setTitleBgColor(getResources().getColor(R.color.black_eee))
                .setCancelColor(getResources().getColor(R.color.text_cancel_color))
                .setSubmitColor(getResources().getColor(R.color.text_submit_color))
                .setTextColorCenter(getResources().getColor(R.color.colorPrimary))
                .isRestoreItem(true)//切换时是否还原，设置默认选中第一项。
                .setOutSideColor(getResources().getColor(R.color.translucence)) //设置外部遮罩颜色
                .setOptionsSelectChangeListener(new OnOptionsSelectChangeListener() {
                    @Override
                    public void onOptionsSelectChanged(int options1, int options2, int options3) {

                    }
                })
                .build();

        pvOptions.setSelectOptions(positionArray[0]);
        pvOptions.setPicker(deptList);//进入页面就获取，默认不显示
        pvOptions.show();

    }

    /**
     * 获取部门
     */
    private void getDeptData() {
        OkGo.<String>post(MyConstant.POST_CONTACTS_DEPT)
                .tag(this)
                .upJson("")
                .execute(new StringDialogCallback(getActivity()) {
                    @Override
                    public void onSuccess(Response<String> response) {
                        String result = response.body();
                        if (!StringUtils.isEmpty(result)) {

                            try {
                                Gson gson = GsonFactory.getSingletonGson();
                                ContactsDeptBean contactsDeptBean = new ContactsDeptBean();
                                contactsDeptBean = gson.fromJson(result, ContactsDeptBean.class);
                                dataBeans = contactsDeptBean.getList();
                                if (dataBeans != null) {
                                    if (dataBeans.size() > 0) {
                                        deptList.clear();
                                        ContactsDeptBean.ListBean listBean = new ContactsDeptBean.ListBean();
                                        listBean.setName("全部部门");
                                        listBean.setDeptId("00");
                                        dataBeans.add(0, listBean);
                                        for (int i = 0; i < dataBeans.size(); i++) {
                                            String deptName = dataBeans.get(i).getName();
                                            deptList.add(deptName);
                                        }
                                    }
                                }


                            } catch (JsonSyntaxException e) {
                                e.printStackTrace();
                                binding.emptyLayout.setIsShowView(true);
                                ToastUtils.showLong(getResources().getString(R.string.text_json_error));
                            }


                        }
                    }
                });
    }
}